<?php
namespace Home\Model;
use Think\Model;
class CommodityLimitModel extends CommonModel {

	public function getLimit($commodity_id,$limit_type=1){
		$res = array();
		$limit_info = $this->where("commodity_id = '".$commodity_id."' and limit_type = '".$limit_type."' and status = 1")->find();
		if(empty($limit_info)){
			$res['is_limit'] = false;
			$res['left_num'] = 0;
		}else{
			$res['is_limit'] = true;
			$res['left_num'] = num_f($limit_info['left_num']);
		}
		return $res;
	}
	
	public function getLimitArr($limit_type=1){
		$res = array();
		$db_res = $this->where(" limit_type = '".$limit_type."' and status = 1")->select();
		foreach($db_res as $db_one){
			$res[$db_one['commodity_id']] = $db_one['left_num'];
		}
		return $res;
	}
	
	public function checkLimit($commodity_id,$commodity_num,$limit_type=1){
		$res = array();
		$limit_info = $this->where("commodity_id = '".$commodity_id."' and 
									limit_type = '".$limit_type."' and 
									status = 1")->find();
		if(empty($limit_info)){
			return true;
		}elseif ($limit_info['left_num']>=$commodity_num){
			return true;
		}else{
			return false;
		}
	}
	
	//操作库存
	public function doLimitByOrder($order_id,$commodity_id,$commodity_num,$limit_type=1,$flag=-1){
		$commodityLimit = D('CommodityLimit');
		$commodityLimitLog = D('CommodityLimitLog');
		if($flag>0){
			$commodityLimit->where("commodity_id = '".$commodity_id."' and limit_type = '".$limit_type."' and status = 1")->setInc("left_num",$commodity_num);
		}else{
			$commodityLimit->where("commodity_id = '".$commodity_id."' and limit_type = '".$limit_type."' and status = 1")->setDec("left_num",$commodity_num);
		}
		$data['commodity_id'] = $commodity_id;
		$data['limit_type'] = $limit_type;
		$data['order_id'] = $order_id;
		$data['change_num'] = $commodity_num*$flag;
		$commodityLimitLog->data($data)->add();
		return true;
	}
}

?>